package ch14;

import javafoundations.LinkedStack;

import java.util.Scanner;

/**
 * Created by zhangyunqi on 2017/10/15.
 */
public class PostfixEvaluator {
    private final char ADD ='+',SUBTRACT='-';
    private final char MULTIPLY='*',DIVIDE='/';
    private LinkedStack<Integer> stack;

    public PostfixEvaluator ()
    {
        stack=new LinkedStack <Integer> ();
    }

    public int evaluate (String expr)
    {
        int op1,op2,result=0;
        String token;
        Scanner tokenizer = new Scanner ( expr );

        while (tokenizer.hasNext ()){
            token=tokenizer.next ();
            if (isOperator(token)){
                op2=(stack.pop ()).intValue ();
                op1=(stack.pop ()).intValue ();
                result=evalSingleOp(token.charAt ( 0 ),op1,op2);
                stack.push ( result );
            }
            else
                stack.push ( Integer.parseInt ( token ) );

        }
        return result;
    }

    private boolean isOperator(String token){
        return (token.equals ( "+" )||token.equals ( "-" )||token.equals ( "*" )||token.equals ( "/" ));
    }

    private int evalSingleOp(char operation,int op1,int op2){
        int result=0;
        switch (operation){
            case ADD:
                result=op1+op2;
                break;

            case SUBTRACT:
                result=op1-op2;
                break;

            case MULTIPLY:
                result=op1*op2;
                break;

            case DIVIDE:
                result=op1/op2;

        }
        return result;
    }
}
